package com.pw.study.flink.sql;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class $01TableBase {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //初始化数据
        DataStreamSource<WaterSensor> data =
                env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60));
        //初始化表环境
        StreamTableEnvironment sEnv = StreamTableEnvironment.create(env);
        //关联关系
        Table table = sEnv.fromDataStream(data);
        //执行查询
        Table result = table.select("*");
        Table tb1 = table.select($("id"), $("ts"), $("vc"));
        Table tb = table.select($("id"), $("ts"), $("vc")).where($("id").isEqual("sensor_1"));
        DataStream<WaterSensor> stream = sEnv.toAppendStream(tb, WaterSensor.class);
        DataStream<Row> row = sEnv.toAppendStream(tb, Row.class);
        row.print("row");
        tb.printSchema();
        stream.print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
